package kr.hyunist.androidcomplete02saeildamil.ch20;

import kr.hyunist.androidcomplete02saeildamil.R;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class FragmentManagerTest extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragmentmanagertest);
	}
	
	public void mOnClick(View v){
		//1. 일단 프래그먼트매니저클래스로 프래그먼트 매니저를 get해와서
		FragmentManager fm = getFragmentManager();
		Fragment fragment = fm.findFragmentById(R.id.fragmentmanagerfl);
		
		switch(v.getId()){
		case R.id.fragmentmanagerbtnadd:
			if(fragment == null){
				//2. 프래그먼트가 null일 경우, 프래그먼트 트랜젝션을 실행 시켜서 카운터프래그먼트를 액티비티 레이아웃 내의 frameLayout에 배치
				FragmentTransaction tr = fm.beginTransaction();
				CounterFragment cf = new CounterFragment();
				tr.add(R.id.fragmentmanagerfl, cf, "counter").commit();
			} else {
				Toast.makeText(this, "이미 추가", 0).show();
			}
			break;
			
		case R.id.fragmentmanagerbtnremove:
			if(fragment == null){
				Toast.makeText(this, "프래그먼트 없음", 0).show();
			} else {
				FragmentTransaction tr = fm.beginTransaction();
				tr.remove(fragment);
				tr.commit();
			}
			break;
			
		case R.id.fragmentmanagerbtnreplace:
			if(fragment == null){
				Toast.makeText(this, "프래그먼트 없음", 0).show();
			} else {
				FragmentTransaction tr = fm.beginTransaction();
				if(fragment.getTag() == "counter"){
					TextFragment tf = new TextFragment();
					tr.replace(R.id.fragmentmanagerfl, tf, "text");
					
				} else {
					CounterFragment cf = new CounterFragment();
					tr.replace(R.id.fragmentmanagerfl, cf, "counter");
					
				}
				
				tr.commit();
			}
			break;
			
		case R.id.fragmentmanagerbtnhide:
			if(fragment == null){
				Toast.makeText(this, "프래그먼트 없음", 0).show();
			} else {
				FragmentTransaction ft = fm.beginTransaction();
				if(fragment.isHidden()){
					ft.show(fragment);
				} else {
					ft.hide(fragment);
				}
				ft.commit();
			}
			break;
		}
	}
}
